<template>
  <div class="alarm-notice-container">
    <div class="header-box">
      <van-dropdown-menu active-color="#3378FF">
        <van-dropdown-item
          v-model="level"
          :options="levelOption"
          @change="changeLevel"
        />
      </van-dropdown-menu>
      <div class="choose-date">
        <i class="iconfont iconrili"></i>
        <div
          class="choose-date-text"
          v-if="chooseDate"
        >
          <span @click="showDate = true">{{ chooseDate }}</span>
          <van-icon
            name="cross"
            @click="clearChooseDate"
          />
        </div>
        <span
          v-else
          @click="showDate = true"
        >开始时间-结束时间</span>
      </div>
    </div>

    <ul
      class="record-list scroll-box"
      v-if="alarmList.length"
      @scroll="scrollFn"
    >
      <li
        v-for="item in alarmList"
        :key="item.id"
        @click="jumpDetail(item)"
      >
        <div class="item-left">
          <i class="iconfont iconyubaojing"></i>
        </div>
        <div class="item-right">
          <div class="item-right-top">
            <p class="item-level-date">
              <span
                class="item-level"
                v-if="item.grade"
              >{{ coverGrade(item.grade) }}</span>
              <span class="item-date">{{ item.time }}</span>
            </p>
            <p
              class="status-box"
              v-if="item.status === 1"
            >
              <span class="status-icon purple-bg">
                <i class="iconfont icondaiqueren"></i>
              </span>
              待确认
            </p>
            <p
              class="status-box"
              v-if="item.status === 2"
            >
              <span class="status-icon yellow-bg">
                <i class="iconfont icondaichuli"></i>
              </span>
              待处理
            </p>
            <p
              class="status-box"
              v-if="item.status === 3"
            >
              <span class="status-icon blue-bg">
                <i class="iconfont iconchulizhong"></i>
              </span>
              处理中
            </p>
            <p
              class="status-box"
              v-if="item.status === 5"
            >
              <span class="status-icon green-bg">
                <i class="iconfont icontianjiawancheng"></i>
              </span>
              处理完成
            </p>
            <p
              class="status-box color-green"
              v-if="item.status === 6"
            >
              已恢复
            </p>
          </div>
          <div class="item-right-center">
            <span>故障名称</span>
            <span>故障代码</span>
          </div>
          <div class="item-right-bottom">
            <span>{{ item.errorName }}</span>
            <span>{{ item.errorCode }}</span>
          </div>
        </div>
      </li>

      <!-- 加载状态 -->
      <div
        class="loading-box"
        v-if="loading"
      >
        <p
          class="finished"
          v-if="finished"
        >没有更多了</p>
        <div
          class="loading"
          v-else
        >
          <van-loading size="14px">加载中...</van-loading>
        </div>
      </div>
    </ul>

    <div
      class="no-data-box"
      v-if="noDataState"
    >暂无数据</div>

    <van-calendar
      v-model="showDate"
      type="range"
      color="#3378ff"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onConfirm"
      ref="calendar"
    />
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { DropdownMenu, DropdownItem, Calendar, Loading } from 'vant';
import { getDeviceAlarmList } from '@/api/deviceManage.js';
import { getAlarmNoticeDetail } from '@/api/maintenanceAlarmNotification';

export default {
  name: 'AlarmNotice',
  components: {
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Calendar.name]: Calendar,
    [Loading.name]: Loading
  },
  data() {
    return {
      level: '',
      levelOption: [],
      showDate: false,
      minDate: new Date('2021-01-01'),
      maxDate: new Date(),
      alarmList: [],
      beginTime: '',
      endTime: '',
      chooseDate: '',
      pageIndex: 1,
      pageSize: 10,
      loading: false, //加载状态
      finished: false, //全部加载
      noDataState: false //无数据显示状态
    };
  },
  created() {
    this.createLevelData();
    this.getDeviceAlarmList();
  },
  methods: {
    // 创建等级选项
    createLevelData() {
      let levelArr = ['全部等级', '一级', '二级', '三级', '四级', '五级'];
      levelArr.map((item, index) => {
        this.levelOption.push({
          text: item,
          value: index === 0 ? '' : index
        });
      });
    },
    // 获取列表数据
    getDeviceAlarmList() {
      getDeviceAlarmList({
        id: this.$route.query.id,
        grade: this.level,
        beginTime: this.beginTime,
        endTime: this.endTime,
        page: this.pageIndex,
        page_size: this.pageSize
      }).then(res => {
        this.loading = false;
        let data = res.data.list || [];
        data.map(item => {
          item.time = item.time.replace('T', ' ').substr(0, 19);
        });
        this.alarmList = this.alarmList.concat(data);

        // 无数据
        if (this.alarmList.length <= 0 && this.pageIndex === 1) {
          this.noDataState = true;
          this.loading = false;
          this.finished = false;
        }

        // 全部加载完成
        if (this.pageIndex > 1 && res.data.list.length < this.pageSize) {
          this.finished = true;
        }
      });
    },
    // 切换等级
    changeLevel(value) {
      this.grade = value;
      this.reloadData();
    },
    // 确定时间选择
    onConfirm(value) {
      this.beginTime = `${dayjs(value[0]).format('YYYY-MM-DD')} 00:00:00`;
      this.endTime = `${dayjs(value[1]).format('YYYY-MM-DD')} 23:59:59`;
      this.chooseDate = `${dayjs(value[0]).format('YYYY-MM-DD')} - ${dayjs(value[1]).format('YYYY-MM-DD')}`;
      this.showDate = false;
      this.reloadData();
    },
    // 清除时间选择
    clearChooseDate() {
      this.$refs.calendar.reset();
      this.beginTime = '';
      this.endTime = '';
      this.chooseDate = '';
      this.reloadData();
    },
    // 重新加载数据
    reloadData() {
      this.loading = false;
      this.finished = false;
      this.noDataState = false;
      this.pageIndex = 1;
      this.alarmList = [];
      this.getDeviceAlarmList();
    },
    // 等级转换为文字
    coverGrade(grade) {
      let obj = {
        1: '一级',
        2: '二级',
        3: '三级',
        4: '四级',
        5: '五级'
      };
      return obj[grade];
    },
    // 滚动事件
    scrollFn(e) {
      let scrollTop = document.querySelector('.record-list').scrollTop;
      let clientHeight = document.querySelector('.record-list').clientHeight;
      let scrollHeight = document.querySelector('.record-list').scrollHeight;

      if (scrollTop + clientHeight >= scrollHeight) {
        this.$debounceFn(this.onLoadMore, 300);
      }
    },
    // 加载更多
    onLoadMore() {
      this.loading = true;
      if (!this.finished) {
        // 异步更新数据
        setTimeout(() => {
          this.pageIndex++;
          this.getDeviceAlarmList();
        }, 500);
      }
    },
    // 报警详情
    jumpDetail(item) {
      getAlarmNoticeDetail({
        id: item.id
      }).then(res => {
        if (this.$checkBtnPermission('maintenanceCenter:alarmNotice:list:detail')) {
          localStorage.setItem('deviceDetailTab', '报警通知');
          // 有工单时，跳转到工单详情，没有时跳转到报警详情
          let status = [1, 2, 6];
          if (status.includes(res.data.status)) {
            // 报警详情
            this.$router.push({
              name: 'alarmNotificationDetail',
              query: {
                id: res.data.id,
                from: 'other'
              }
            });
          } else {
            // 工单详情
            this.$router.push({
              name: 'alarmWorkDetail',
              query: {
                id: res.data.orderId
              }
            });
          }
        } else {
          this.$toast(this.$store.state.noDetailPermissionText);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.alarm-notice-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .header-box {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    height: 1.44rem;
    border-bottom: 1px solid var(--border-color);

    .van-dropdown-menu {
      width: 3.733333rem;
      height: 100%;
      background-color: #fff;

      ::v-deep .van-dropdown-menu__bar {
        height: 100%;
        box-shadow: unset;
      }
    }

    .choose-date {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: var(--color-deep-gray);
      font-size: 0.373333rem;
      background-color: #fff;

      i {
        margin-right: 0.106667rem;
      }

      .choose-date-text {
        .van-icon {
          margin-left: 0.16rem;
        }
      }
    }
  }

  .record-list {
    flex: 1;
    padding-bottom: 0.213333rem;

    li {
      display: flex;
      align-items: center;
      margin-top: 0.213333rem;
      padding: 0.426667rem;
      background-color: #fff;

      .item-left {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 1.12rem;
        height: 1.12rem;
        margin-right: 0.32rem;
        border-radius: 50%;
        background-color: #fef0f0;

        i {
          font-size: 0.586667rem;
          color: var(--color-red);
        }
      }

      .item-right {
        position: relative;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding-left: 0.32rem;

        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 1px;
          height: 100%;
          background-color: var(--border-color);
        }

        .item-right-top {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .item-level-date {
            display: flex;
            align-items: center;

            .item-level {
              margin-right: 0.106667rem;
              padding: 0.053333rem;
              color: var(--color-primary);
              font-size: 0.266667rem;
              border: 1px solid #85aeff;
              border-radius: 0.053333rem;
            }
            .item-date {
              font-size: 0.4rem;
            }
          }

          .status-box {
            display: flex;
            align-items: center;
            font-size: 0.32rem;

            &.color-green {
              color: #67c23a;
            }

            .status-icon {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 0.426667rem;
              height: 0.426667rem;
              margin-right: 0.106667rem;
              border-radius: 50%;
              color: #fff;

              &.yellow-bg {
                background-color: #ffc329;
              }

              &.green-bg {
                background-color: #81e4a9;
              }

              &.blue-bg {
                background-color: #76b6ff;
              }

              &.purple-bg {
                background-color: #a788ff;
              }

              i {
                font-size: 0.266667rem;
              }
            }

            color: var(--color-deep-gray);
          }
        }

        .item-right-center {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 0.32rem 0 0.213333rem;
          font-size: 0.32rem;
          color: var(--color-deep-gray);
        }

        .item-right-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 0.32rem;
          color: var(--color-gray);

          span {
            &:first-of-type {
              margin-right: 0.266667rem;
            }

            &:last-of-type {
              flex-shrink: 0;
            }
          }
        }
      }
    }
  }

  .no-data-box {
    padding: 0.32rem 0.426667rem;
    text-align: center;
    color: var(--color-gray);
    font-size: 0.373333rem;
  }
}
</style>